package com.lz.ub.core

import com.lz.ub.COMMAND_CONNECTED_DELAYED
import com.lz.ub.UBCDevice
import com.lz.ub.UBCOperator
import com.lz.ub.UBCWritable
import java.util.*

/**
 * @author You
 * 主板UUID服务设置器, 设置此步才可正常读写操作, 每一台从机都设置一次UUID, 主板只设置一次会有指令收不到的情形
 */
internal class UBCServing(private val operator: UBCOperator) : UBCWritable {

    //待UUID服务的设备
    private val pendingDevices = LinkedList<UBCDevice>()

    //当前正在服务的设备
    private var currentDevice: UBCDevice? = null

    //推入要连接的设备, 推入前要判断状态[isAvailable]
    fun pushPendingDevices(devices: List<UBCDevice>) {
        pendingDevices.addAll(devices)
        next(false)
    }

    //推入要连接的单个设备
    fun pushPendingDevice(device: UBCDevice) {
        pendingDevices.add(device)
        next(false)
    }

    private fun next(delayed: Boolean) {
        currentDevice = pendingDevices.pollFirst()
        if (currentDevice != null) {
            val device = currentDevice!!
            if (device.needServing()) {
                if (delayed) Thread.sleep(COMMAND_CONNECTED_DELAYED)
                operator.write(device.serviceCmd, this)
            } else {
                next(delayed)
            }
        } else {
            operator.servingOver()
        }
    }

    override val label: String = "Serving"

    override fun responseOk() {
        currentDevice?.serving()
        next(true)
    }

    override fun responseFail() {
        next(true)
    }

    override fun close() {
        pendingDevices.clear()
        currentDevice = null
    }

    override fun isAvailable(): Boolean = pendingDevices.isEmpty() && currentDevice == null
}